"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 文章-分类接口
 */
class BlogCategoryController extends Controller {
  /**
   * @summary 给博客设置分类
   * @router patch /api/blog-category/setCategory
   * @request query number blogId 博客ID
   * @request query number categoryId 分类ID
   * @apikey
   */
  async setCategory() {
    const { ctx } = this;
    const { blogId, categoryId } = ctx.query;
    const blog = await ctx.model.Blog.findByPk(blogId);
    const category = await ctx.model.Category.findByPk(categoryId);
    if (blog === null || category === null) {
      ctx.body = {
        code: 404,
        msg: "博客或分类不存在",
        data: ctx.query,
      };
      return;
    }
    blog.categoryId = category.categoryId;
    await blog.save();
    ctx.body = {
      code: 200,
      msg: "设置博客分类",
      data: ctx.query,
    };
  }

  /**
   * @summary 查询某分类下的博客
   * @router get /api/blog-category/getBlogByCategory
   * @request query number categoryId 分类id
   * @apikey
   */
  async getBlogByCategory() {
    const { ctx } = this;
    const categoryId = ctx.query.categoryId;
    const res = await ctx.model.Blog.findAndCountAll({
      attributes: { exclude: ["content"] },
      where: { categoryId },
      order: [["created_at", "DESC"]],
    });
    ctx.body = {
      code: 200,
      msg: "查询某分类下的博客",
      data: {
        total: res.count,
        blogList: res.rows,
      },
    };
  }
}

module.exports = BlogCategoryController;
